package Java.view.Common;

import Java.utils.CodeUtils;
import Java.utils.JDBC;
import domain.User;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;

public class RegisterFX extends Application {
    private String codeText = "";
    private String usernameText = "";
    private String passwordText = "";
    private String rePasswordText = "";
    private String rightcodeText = "";

    private TextField username = new TextField();
    private PasswordField password = new PasswordField();
    private PasswordField rePassword = new PasswordField();
    private TextField code = new TextField();
    private Label rightCode = new Label();
    private Label goLogin = new Label();
    private Button register = new Button();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("注册");
        primaryStage.getIcons().add(new Image("file:src/image/dizhu.png"));
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(20));

        GridPane grid = new GridPane();
        grid.setHgap(20);
        grid.setVgap(16);
        grid.setPadding(new Insets(90,80,80,220));

        // 把输入框添加到容器内
        grid.add(username, 1, 0);
        grid.add(password, 1, 1);
        grid.add(rePassword, 1, 2);
        grid.add(code, 1, 3);
        grid.add(rightCode, 2, 3);
        grid.add(register, 1, 6);
        grid.add(goLogin,1,7);
        root.setCenter(grid);
        GridPane.setHalignment(rightCode, HPos.LEFT); // 设置水平对齐方式
        GridPane.setMargin(rightCode, new Insets(0, 0, 0, -7)); // 设置左边距，调整标签位置
        // 背景图片
        BackgroundImage myBI = new BackgroundImage(new Image("file:src/image/login/shouye2.png", 633, 405, false, true),
                BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
                BackgroundSize.DEFAULT);
        root.setBackground(new Background(myBI));

        //把他们显示出来
        initView();
        initEvents();

        Scene scene = new Scene(root, 633, 405);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initView() {
        rightCode.setText(CodeUtils.getCode());
        rightCode.setMinSize(55, 30);  // 设置最小大小
        rightCode.setAlignment(Pos.CENTER);  // 文字居中显示
        rightCode.setOnMouseClicked(e -> {
            rightCode.setText(CodeUtils.getCode());
        });
        rightCode.setStyle("-fx-border-color: gray; -fx-background-color: white; -fx-padding: 5;");

        register.setGraphic(new ImageView(new Image("file:src/image/login/注册按钮.png")));
        register.setStyle("-fx-background-color: transparent;");
        register.setOnMousePressed(event -> register.setGraphic(new ImageView(new Image("file:src/image/login/注册按下.png"))));
        register.setOnMouseReleased(event -> register.setGraphic(new ImageView(new Image("file:src/image/login/注册按钮.png"))));

        // 去登陆
        goLogin.setText("     已有帐号？ 去登陆");
        goLogin.setStyle("-fx-text-fill: yellow; -fx-font-style: italic;");
        goLogin.setCursor(javafx.scene.Cursor.HAND);
    }

    private void initEvents() {
        register.setOnMouseClicked(event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                usernameText = username.getText();
                passwordText = password.getText();
                rePasswordText = rePassword.getText();
                codeText = code.getText();
                rightcodeText = rightCode.getText();

                try {
                    if (isExist(usernameText)) {
                        showAlert("用户名已存在！");
                        rightCode.setText(CodeUtils.getCode());
                    } else {
                        if (Objects.equals(usernameText, "") || Objects.equals(passwordText, "")) {
                            showAlert("用户名或密码不能为空！");
                            rightCode.setText(CodeUtils.getCode());
                        } else if (!Objects.equals(rePasswordText, passwordText)) {
                            showAlert("两次密码不一致！");
                            rightCode.setText(CodeUtils.getCode());
                        } else if (Objects.equals(codeText, "")) {
                            showAlert("验证码不能为空！");
                            rightCode.setText(CodeUtils.getCode());
                        } else if (!codeText.equals(rightcodeText)) {
                            showAlert("验证码错误！");
                            rightCode.setText(CodeUtils.getCode());
                        } else {
                            User user = new User(usernameText);
                            user.setPassword(passwordText);
                            user.setHappyDou(0);
                            user.setExp(0);

                            Connection connection = JDBC.getConnection();
                            Statement statement = connection.createStatement();
                            String sql = String.format("INSERT INTO user (username, password, happyDou, exp) VALUES ('%s', '%s', %d, %d)",
                                    user.getUsername(), passwordText, 0, 0);
                            statement.executeUpdate(sql);

                            new LoginFX(user).start(new Stage());
                            ((Stage) register.getScene().getWindow()).close();
                        }
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        goLogin.setOnMouseClicked(event -> {
            new LoginFX(null).start(new Stage());
            ((Stage) goLogin.getScene().getWindow()).close();
        });

        rightCode.setOnMouseClicked(event -> {
            rightCode.setText(CodeUtils.getCode());
        });
    }

    private boolean isExist(String usernameText) throws SQLException {
        Connection connection = JDBC.getConnection();
        String sql = "SELECT * FROM user WHERE username='" + usernameText + "'";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        return resultSet.next();
    }

    private void showAlert(String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
